#coding=utf-8

import subprocess
import shutil
import json
import os
import sys

COMMENT = """
 ##############################################
##                oh_hap_tool                 ##
 ##############################################
"""

hap_ext_len = len(".hap")

def build_graphics_profile_hap(config_map, hap_path):
    hap_dir = unpack_hap(config_map, hap_path)
    
    copy_graphics_profile_file(config_map, hap_dir)
    packageNormalize(config_map, hap_dir)

    pack_hap_path = pack_hap(config_map, hap_dir)
    sign_hap(config_map, pack_hap_path)
    pass

def unpack_hap(config_map, hap_path):
    hap_dir = hap_path[:-hap_ext_len]
    cmd_list = ["java", "-jar", "app_unpacking_tool.jar", "--mode", "hap", "--hap-path", hap_path, "--out-path", hap_dir, "--force", "true"]
    process_call(cmd_list)
    return hap_dir

def pack_hap(config_map, hap_dir):
    hap_path = hap_dir + "_pack.hap"
    if os.path.exists(hap_path):
        os.remove(hap_path)

    module_json = hap_dir + "/module.json"
    resources_path = hap_dir + "/resources"
    ets_path = hap_dir + "/ets"
    resources_index =  hap_dir + "/resources.index"
    pack_info = hap_dir + "/pack.info"
    lib_path = hap_dir + "/libs"
    
    cmd_list = ["java", "-jar", "app_packing_tool.jar", "--mode", "hap", "--json-path", module_json, "--resources-path", resources_path, "--ets-path", ets_path, "--index-path", resources_index, "--pack-info-path", pack_info, "--lib-path", lib_path, "--out-path", hap_path]
    process_call(cmd_list)
    return hap_path
    pass

def sign_hap(config_map, hap_path):
    keyAlias = config_map["keyAlias"]
    keyPwd = config_map["keyPwd"]
    keystorePwd = config_map["keystorePwd"]
    cer_path = config_map["cer_path"]
    p7b_path = config_map["p7b_path"]
    p12_path = config_map["p12_path"]
    dest_hap_path = append_value_to_hap_name(hap_path, "_sign")
    cmd_list = ["java", "-jar", "hap-sign-tool.jar", "sign-app", "-keyAlias", keyAlias, "-signAlg", "SHA256withECDSA", "-mode", "localSign", "-appCertFile", cer_path, "-profileFile", p7b_path, "-inFile", hap_path, "-outFile", dest_hap_path, "-keyPwd", keyPwd, "-keystorePwd", keystorePwd, "-keystoreFile", p12_path, "-signCode", "1"]
    process_call(cmd_list)
    return dest_hap_path

def process_call(cmd_list):
    cmd_str = " ".join(cmd_list)
    print("[oh_hap_tool](process_call) begin cmd:" + cmd_str)
    process = subprocess.Popen(
        cmd_str, shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT
    )
    while True:
        out = process.stdout.read(1).decode('utf-8', errors='replace')
        if out == '' and process.poll() != None:
            break
        if out != '':
            print(out)
    return_code = process.returncode
    print("[oh_hap_tool](process_call) return_code:", return_code)
    return return_code

def copy_graphics_profile_file(config_map, hap_dir):
    src_libsquid_so = "graphics_profiler/libsquid.so"
    src_squid_json = "graphics_profiler/squid.json"

    dest_libsquid_so = hap_dir + "/libs/arm64-v8a/libsquid.so"
    dest_squid_json = hap_dir + "/resources/rawfile/squid.json"

    shutil.copy2(src_libsquid_so, dest_libsquid_so)
    shutil.copy2(src_squid_json, dest_squid_json)
    pass

def packageNormalize(config_map, hap_dir):
    bundle_name = config_map["normal_bundle_name"]

    # 修改 module.json
    module_json = hap_dir + "/module.json"
    with open(module_json, 'r', encoding='utf-8') as file:
        data = json.load(file)
    data['app']['bundleName'] = bundle_name
    with open(module_json, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)
    
    # 修改 pack.info
    pack_info = hap_dir + "/pack.info"
    with open(pack_info, 'r', encoding='utf-8') as file:
        data = json.load(file)
    data['summary']['app']['bundleName'] = bundle_name
    with open(pack_info, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)
    

def append_value_to_hap_name(hap_path, value):
    return hap_path[:-hap_ext_len] + value + hap_path[-hap_ext_len:]

if __name__ == '__main__':
    print(COMMENT)
    import argparse
    parser = argparse.ArgumentParser(description=u'oh hap tools!')
    parser.add_argument('-type', required=True, choices=['build_graphics_profile_hap', 'unpack_hap', 'pack_hap', 'sign_hap'], help=u'choices build_graphics_profile_hap, pack_hap, unpack_hap, sign_hap')
    parser.add_argument('-input_path', required=True, help=u'input path')
    args = parser.parse_args()

    if os.path.exists(args.input_path):
        args.input_path = os.path.abspath(args.input_path)
    
    config_map = {
        "normal_bundle_name": "com.odin.graphicsprofile",
        "keyAlias": "odin",
        "keyPwd": "123abCD_",
        "keystorePwd": "123abCD_",
        "cer_path": os.path.abspath("oh_cer/development.cer"),
        "p7b_path": os.path.abspath("oh_cer/GraphicsProfileDebug.p7b"),
        "p12_path": os.path.abspath("oh_cer/odin.p12"),
    }
    if args.type == "build_graphics_profile_hap":
        build_graphics_profile_hap(config_map, args.input_path)
        pass
    elif args.type == "unpack_hap":
        unpack_hap(config_map, args.input_path)
        pass
    elif args.type == "pack_hap":
        pack_hap(config_map, args.input_path)
        pass
    elif args.type == "sign_hap":
        sign_hap(config_map, args.input_path)
        pass